<script type="text/javascript">
// socket参数
let timeout = 10 * 1000; // 4 5秒一次心跳
let timeoutObj = null // 心跳心跳倒计时
let serverTimeoutObj = null // 心跳倒计时
let timeoutnum = null // 断开 重连倒计时
let lockReconnect = false // 防止
let websocket = null

let headers = [];

let device = {};
// const BASE_URL = "192.168.0.10:8001/";
const BASE_URL = "192.168.2.37:8001/";
// const BASE_URL = "49.234.13.30:8888/";

function initWebSocket() {
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    let wsUrl = `ws://${BASE_URL}v1/ws`;
    websocket = new WebSocket(wsUrl);
    websocket.onopen = websocketonopen;
    websocket.onerror = websocketonerror;
    websocket.onmessage = setOnmessageMessage;
    websocket.onclose = websocketclose;
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    // window.onbeforeunload = that.onbeforeunload
}
function start() {
    //清除延时器
    timeoutObj && clearTimeout(timeoutObj);
    serverTimeoutObj && clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(() => {
        if (websocket && websocket.readyState == 1) {
            console.error("TAG 心跳包：", headers);
            if (headers.length > 5) {//有5 次没有收到回包了
                window.dispatchEvent(new CustomEvent("SOCKET_CLOSE"));
                websocket.close && websocket.close();
                return;
            }
            websocket.send(JSON.stringify(
                {
                    Protocol: 1,
                }
            ));//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
            headers.push("C00000");
        } else {
            reconnect();
        }
        //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        serverTimeoutObj = setTimeout(() => {
            window.dispatchEvent(new CustomEvent("SOCKET_CLOSE"));
            websocket.close && websocket.close();
        }, timeout)
    }, timeout)
}
function reset() { // 重置心跳
    // 清除时间
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    // 重启心跳
    start();
}
// 重新连接
function reconnect() {
    if (lockReconnect) return
    lockReconnect = true;
    window.dispatchEvent(new CustomEvent("SOCKET_CLOSE"));
    //没连接上会一直重连，设置延迟避免请求过多
    timeoutnum && clearTimeout(timeoutnum);
    timeoutnum = setTimeout(() => {
        initWebSocket();
        lockReconnect = false;
    }, 5000)
}
function setOnmessageMessage(event) {
    try {
        if (!event.data) {
            console.error("TAG 没有数据");
            return;
        }
        var value = JSON.parse(event.data);
        console.error("Message获得消息:", value);
        if (!value.success) {
            // alert(value.msg);
            return;
        }
        if (value.protocol == 1) {//是心跳的就不往下面处理了
            reset();
            headers.shift();
            return;
        }
        switch (value.protocol) {
            case 1000://登录成功
                start();
                break;
            case 4://刷新显示
                let d = value.data;
                window.dispatchEvent(new CustomEvent('REFRESH', {
                    detail: d
                }));
                return;
            case 2:
                location.reload();
                return;
        }
        window.dispatchEvent(new CustomEvent('SOCKET_MESSAGE', {
            detail: value
        }));
    } catch (e) {
        console.error(e);
        // alert(e.messsage);
    }
}
function websocketonopen() {//连接成功,开始登录
    //开启心跳
    // start();
    console.log("WebSocket连接成功!!!" + new Date() + "----" + websocket.readyState);
    window.dispatchEvent(new CustomEvent("OPEN_SOCKET"));
}
function websocketonerror(e) {
    console.log("WebSocket连接发生错误" + e);
    window.dispatchEvent(new CustomEvent("SOCKET_CLOSE"));
}

function websocketclose(e) {
    websocket.close();
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    console.log("WebSocket连接关闭");

    window.dispatchEvent(new CustomEvent("SOCKET_CLOSE"));

    reconnect();
}
function websocketsend(messsage) {
    websocket && websocket.send(messsage)
}
function closeWebSocket() { // 关闭websocket
    websocket && websocket.close()
}


//颜色配置
let colorConfig = {
    backgroundColor: "#1D82E8",
    textColor: "#FFFFFF",
    contentColor: "#1E55A8",
    readyColor: "rgba(14, 115, 243, 0.8)",
    currentColor: "rgba(255, 255, 255, 0.1)"
};


export default
    {
        colorConfig,
        device,
        BASE_URL,

        initWebSocket,
        websocketsend,
    }
</script>